package sw6.bmi.profile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import sw6.bmi.MainActivity;
import sw6.lib.Settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;


public class EditImageActivity extends Activity {

	private static final int TAKE_PHOTO_CODE = 1;
	public static final int sRESULT_NEW_IMG = 1001;
	public static final int sRESULT_NO_NEW_IMG = 1002;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		takePhoto();
	}
	
	private void takePhoto(){
		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
		startActivityForResult(intent, TAKE_PHOTO_CODE);
	}

	private File getTempFile(Context context){
		//it will return /sdcard/sw6.bmi.profileImage.tmp
		final File path = new File(Environment.getExternalStorageDirectory(), context.getPackageName());
		if(!path.exists()){
			path.mkdir();
		}
		return new File(path, "sw6.bmi.profileImage.tmp");
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch(requestCode){
			case TAKE_PHOTO_CODE:
				final File file = getTempFile(this);
				try {
					Bitmap captureBmp = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
					Settings.setObject(this, MainActivity.sSETTING_OBJECT_IMAGE, new Image(captureBmp));
					setResult(sRESULT_NEW_IMG);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			}
		} else {
			setResult(sRESULT_NO_NEW_IMG);
		}
		finish();
	}
}
